package com.linkit.main.article;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import com.linkit.config.MediaType;
import com.linkit.main.widget.ExtendedImageView;
import com.linkit.utils.Constants;

public class ImageLoader extends AsyncTask<String, Void, Bitmap> {

	private final ExtendedImageView imageView;
	private int type;

	public ImageLoader(int type, ExtendedImageView view) {
		this.imageView = view;
		this.type = type;
	}

	@Override
	protected Bitmap doInBackground(String... params) {
		Bitmap bitmap = null;
		InputStream inputStream = null;
		HttpURLConnection urlConnection = null;
		try {
			URL url = new URL(params[0]);
			
			//mở cổng kết nối dữ liệu
			urlConnection = (HttpURLConnection) url.openConnection();
			
			// Kết nối đến tài nguyên
			urlConnection.connect();
			
			if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				// Reading data from url
				inputStream = urlConnection.getInputStream();

			} else {
				Log.e(Constants.TAG, "Response Code:" + urlConnection.getResponseCode());
			}
			
			//decode lại ảnh từ stream
			bitmap = BitmapFactory.decodeStream(inputStream);
			
		} catch (Exception e) {
			Log.e("","URL = " + params[0], e);
		}finally{
			if(inputStream != null){
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			}
			
			if (urlConnection != null) {
				urlConnection.disconnect();
			}

		}
		return bitmap;
	}

	@Override
	protected void onPostExecute(Bitmap bitmap) {
		if (imageView != null && bitmap != null) {
			if(type == MediaType.IMAGE.getId()){
				imageView.setImage(bitmap);
			}else if(type == MediaType.VIDEO.getId()){
				imageView.setVideoImage(bitmap);
			}
		}
	}
}
